package com.rzico.sbl.ui.report.invite

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDispatchGoodsBinding
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.ReportGoodsData
import com.rzico.sbl.viewmodel.ReportInviteViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.slimadapter.SlimAdapter

class ReportInviteGoodsActivity : BaseActivity(R.layout.activity_report_dispatch_goods) {

    private val mBinding by lazy { ActivityReportDispatchGoodsBinding.bind(getRootView()) }

    private val mKindList = ArrayList<CommonData>()
    private var mKindId = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<ReportInviteViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        getKindData()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关商品信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<ReportGoodsData>(R.layout.item_goods_list) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_goods_has)
                            gone(R.id.item_goods_tag)

                            text(R.id.item_goods_name, bean.name)
                            text(R.id.item_goods_price, bean.phPrice.formatDecimal())
                            text(R.id.item_goods_stock, "")

                            with<ImageView>(R.id.item_goods_logo) {
                                it.loadImage(bean.thumbnail)
                            }

                            clicked {
                                LiveEventBus
                                    .get("inviteGoods")
                                    .post(bean)

                                finishView()
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    private fun initTabLayout() {
        mBinding.goodsTab.apply {
            onTabSelectedListener {
                onTabSelected {
                    it?.let {
                        mKindId = mKindList[it.position].id

                        getViewModel().cancelRequest()
                        getViewModel().delay { updateList() }
                    }
                }
            }

            mKindList.forEachIndexed { index, bean ->
                addTab(newTab().setText(bean.name), index == 0)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .goodsSearch
            .apply {
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入关键字")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入关键字")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    /**
     * 商品分类
     */
    private fun getKindData() {
        getViewModel()
            .kindList(intent.getExtra("shopId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mKindList.add(
                        CommonData().apply {
                            id = ""
                            name = "全部"
                        }
                    )
                    mKindList.addItems(list.filter { it.name == "桶装水" || it.name == "瓶装水" })

                    initTabLayout()
                }
            )
    }

    /**
     * 商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                shopId = intent.getExtra("shopId"),
                kindId = mKindId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout.emptyView.gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}